<template>
  <div>
    <div class="top">
      <!-- 查询表单 -->
      <el-form :inline="true" @submit.prevent>
        <el-form-item label="类型" style="width: 200px">
          <el-select v-model="queryForm.ctypeid" placeholder="请选择类型">
            <el-option
              v-for="type in carTypes"
              :key="type.id"
              :label="type.name"
              :value="type.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品牌" style="width: 200px">
          <el-select v-model="queryForm.brandid" placeholder="请选择品牌">
            <el-option
              v-for="brand in carBrands"
              :key="brand.id"
              :label="brand.name"
              :value="brand.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车牌">
          <el-input
            v-model="queryForm.plate"
            placeholder="请输入车牌号"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否在线" style="width: 200px">
          <el-select v-model="queryForm.isonline" placeholder="请选择状态">
            <el-option label="在线" value="1"></el-option>
            <el-option label="离线" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否删除" style="width: 200px">
          <el-select v-model="queryForm.isdeleted" placeholder="请选择状态">
            <el-option label="未删除" value="0"></el-option>
            <el-option label="已删除" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchCars">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="addCar">
        <el-button type="primary" @click="handleAddCar">+</el-button>
      </div>
    </div>
    <!-- 汽车信息表格 -->
    <el-table :data="cars" stripe border :row-class-name="tableRowClassName">
      <el-table-column
        prop="carname"
        label="车型"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="ctypename"
        label="类型"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="brandname"
        label="品牌"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="plate"
        label="车牌号"
        align="center"
      ></el-table-column>
      <el-table-column label="车辆照片" align="center">
        <template #default="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.pictures"
            :preview-src-list="[scope.row.pictures]"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="price"
        label="价格"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="status"
        label="库存"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" align="center" width="200">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="viewCarDetails(scope.row)"
          >
            查看详情
          </el-button>
          <el-button size="small" type="danger" @click="deleteCar(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="是否在线" align="center">
        <template #default="scope">
          <el-switch
            v-model="scope.row.isonline"
            :active-value="1"
            :inactive-value="0"
            @change="updateCarStatus(scope.row, 'isonline')"
          />
        </template>
      </el-table-column>

      <el-table-column label="是否删除" align="center">
        <template #default="scope">
          <el-switch
            v-model="scope.row.isdeleted"
            :active-value="1"
            :inactive-value="0"
            @change="updateCarStatus(scope.row, 'isdeleted')"
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      :page-size="pageSize"
      @current-change="handlePageChange"
    ></el-pagination>
    <!-- 添加车辆 -->
    <AddCar
      :title="addCarTitle"
      :carTypes="carTypes"
      :carBrands="carBrands"
      @fetchCars="fetchCars"
      ref="addCarRef"
    ></AddCar>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import api from "@/util/service";
import { useLoginStore } from "@/stores/userStores";
import { ElMessage, ElMessageBox } from "element-plus";
import AddCar from "@/components/AddCar.vue";
import { useRouter } from "vue-router";

const userStore = useLoginStore();
const cars = ref([]);
const total = ref(0);
const pageSize = ref(5);
const currentPage = ref(1);

const queryForm = ref({
  ctypeid: null,
  brandid: null,
  plate: "",
  isonline: null,
  isdeleted: null,
});
const carTypes = reactive([]);
const carBrands = reactive([]);
const addCarRef = ref(null);
const addCarTitle = ref("新增车辆");

const fetchCars = async () => {
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    ...queryForm.value,
    lid: userStore.getLid,
  };
  try {
    const response = await api.post("/tcar/selectCars", params);
    if (response.code == 200) {
      cars.value = response.data.records;
      total.value = response.data.total;

      // 清空原有数据
      carTypes.length = 0;
      carBrands.length = 0;

      // 创建唯一类型和品牌集合
      const uniqueTypes = new Set();
      const uniqueBrands = new Set();

      cars.value.forEach((e) => {
        uniqueTypes.add(e.ctypename);
        uniqueBrands.add(e.brandname);
      });

      // 转换为选项对象格式
      Array.from(uniqueTypes).forEach((type, index) => {
        carTypes.push({ id: index + 1, name: type });
      });

      Array.from(uniqueBrands).forEach((brand, index) => {
        carBrands.push({ id: index + 1, name: brand });
      });
    }
  } catch (error) {
    console.error("修改失败:", error);
  }
};

const handlePageChange = (newPage) => {
  currentPage.value = newPage;
  fetchCars();
};

const resetForm = () => {
  queryForm.value = {
    ctypeid: null,
    brandid: null,
    plate: "",
    isonline: null,
    isdeleted: null,
  };
  fetchCars(); // 重置后重新获取数据
};

const tableRowClassName = ({ rowIndex }) => {
  if (rowIndex % 2 === 0) {
    return "warning-row";
  } else {
    return "success-row";
  }
};

const updateCarStatus = async (row, field) => {
  try {
    const params = {
      carid: row.carid,
      [field]: row[field],
    };

    const response = await api.post("/tcar/updateCar", params);

    if (response.code === 200) {
      ElMessage.success("状态更新成功");
    } else {
      row[field] = !row[field];
      ElMessage.error("状态更新失败，请稍后重试");
    }
  } catch (error) {
    row[field] = !row[field];
    console.error("修改失败:", error);
    ElMessage.error("状态更新失败，请稍后重试");
  }
};

const handleAddCar = () => {
  addCarRef.value.openDialog();
};
//删除车辆
const router = useRouter();

// 查看详情
const viewCarDetails = (row) => {
  // 跳转到车辆详情页面，传递车辆ID
  sessionStorage.setItem("carId", row.carid);
  router.push("/CarDetails");
};

// 删除车辆
const deleteCar = (row) => {
  ElMessageBox.confirm(`确定要删除车辆 "${row.carname}" 吗？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const response = await api.post("/tcar/deleteCar", {
          carid: row.carid,
        });

        if (response.code === 200) {
          ElMessage.success("删除成功");
          fetchCars(); // 刷新列表
        } else {
          ElMessage.error("删除失败，请稍后重试");
        }
      } catch (error) {
        console.error("删除失败:", error);
        ElMessage.error("删除失败，请稍后重试");
      }
    })
    .catch(() => {
      // 用户取消删除
    });
};
onMounted(() => {
  fetchCars();
});
</script>

<style scoped>
.el-form-item__content {
  width: 120px;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.top {
  position: relative;
  top: 0;
  left: 0;
}

.addCar {
  position: absolute;
  top: 15px;
  right: 0px;
  display: inline-block;
}
</style>
